// const rsa = require('./jsencrypt/bin/jsencrypt.min.js')
// const parseBigInt = require('./jsencrypt/lib/lib/jsbn/jsbn')
import rsa from './jsencrypt/jsencrypt.min'
import { parseBigInt } from './jsencrypt/jsbn'
// 密钥对生成 http://web.chacuo.net/netrsakeypair; 把下面生成的公钥、私钥换成自己生成的即可
const publicKey = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXtm5htrddYcHi+K3ePCbAXXsmX0cvKYQFKobPLAYvJRxZ/C9/lQ5GR9+QUT2T8wyd9GtpXoQWYy/hV2QliLm9em2hkIBY09iYqHd8QmtLiLxQ66UtvDQDG/oHMNVQFRSS9RVR7TSpNhmC0I2VEfqF/POJim7RuHuPT/ZTB+2dbwIDAQAB'

function en(params) {
  
}
// 加密
function encrypt(txt) {
  const encryptor = new rsa()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
// function decrypt(txt) {
//   const encryptor = new rsa()
//   encryptor.setPublicKey(publicKey) // 设置私钥
//   return encryptor.decrypt(txt) // 对数据进行解密
// }
function pkcs1unpad2(d, n) {
  var b = d.toByteArray()
  var i = 0
  while (i < b.length && b[i] === 0) {
    ++i
  }
  // if (b.length - i !== n - 1 || b[i] !== 2) {
  //   return null
  // }
  ++i
  while (b[i] !== 0) {
    if (++i >= b.length) {
      return null
    }
  }
  var ret = ''
  while (++i < b.length) {
    var c = b[i] & 255
    if (c < 128) { // utf-8 decode
      ret += String.fromCharCode(c)
    } else if ((c > 191) && (c < 224)) {
      ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63))
      ++i
    } else {
      ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63))
      i += 2
    }
  }
  return ret
}

 function decrypt(data) {
    const encrypt = new rsa()
    encrypt.setPublicKey(publicKey)
    // 不支持公钥解密
    // 自定义解析方法支持公钥解析
    const rsaKey = encrypt.getKey()
    rsaKey.decrypt = function(ctext) {
      var c = parseBigInt(ctext,16)
      var m = this.doPublic(c)
      if (m == null) {
        return null
      }
      return pkcs1unpad2(m, (this.n.bitLength() + 7) >> 3)
    }
    return encrypt.decrypt(data)
  }
module.exports = {
  decrypt,
  encrypt
}